/**
 * Created with IntelliJ IDEA.
 * User: xi
 * Date: 13-8-24
 * Time: 上午11:01
 * To change this template use File | Settings | File Templates.
 */

window.BASE_URL = "/services/api";

window.BASE_URL = "/services/api";

var _idMap = {};
var _sendMsg = function (data, callback) {
    _idMap[data.id] = {
        data: data,
        callback: callback
    };// 记录消息以供成功后回调
    parent.window.webSocket_send(data);
}
//websocket回调函数
window.msgCallBack = function (respData) {
    if (respData.status >= 200 && respData.status < 400) {
        var obj = _idMap[respData.id];
        if (obj != null) {
            obj.callback(obj.data, respData);
        }
        console.log('_idMap-device-ctrl:' + respData.id + ':' + obj);
    }
}

var ONLINE_STATE = {online: {v: "在线", c: "greenyellow"}, offline: {v: "离线", c: "gray"}};
window.AllDocCrtl = function ($rootScope, $scope) {
    $scope.queryParams || ( $scope.queryParams = {});
    $scope.queryParams.pageSize = 15;
    $scope.pageItems = {
        all: null, online: null, offline: null
    }
    var loadData = function () {
        $.ajax({
            url: BASE_URL + '/ubun/customer/queryAll',
            type: "GET",
            data: $scope.queryParams,
            dataType: "json",
            success: function (data) {
                $scope.pageData = pageToObj(data);
                $scope.pageItems.all = $scope.pageData.items;
                $scope.pageItems.online = new Array();
                $scope.pageItems.offline = new Array();
                $.each($scope.pageData.items, function (i, item) {
                    if (item.isActive) {
                        item.isActive_show = "";
                    } else {
                        item.isActive_show = "未激活";
                    }
                    if (!item.language) {
                        item.language = "设置";
                    }
                    if (item.conn) {
                        item.online_show = ONLINE_STATE.online.v;
                        item.online_c = ONLINE_STATE.online.c;
                        $scope.pageItems.online.push(item);
                    } else {
                        item.online_show = ONLINE_STATE.offline.v;
                        item.online_c = ONLINE_STATE.offline.c;
                        $scope.pageItems.offline.push(item);
                    }
                    if (item.createTime) {
                        item.createTime_show = (new Date(item.createTime)).format('yyyy-MM-dd hh:mm:ss');
                    }
                    if (item.isLock) {
                        item.isLock = "已锁屏";
                    } else {
                        item.isLock = "";
                    }
                    item.checked = false;
                });
                applyAngularScope($rootScope, $scope);
            }
        });
    }
    loadData();

    $scope.deviceInput = {
        load: function (id, callback) {
            $.ajax({
                url: window.BASE_URL + '/common/device/' + id,
                type: "GET",
                dataType: "json",
                success: function (data) {
                    var formData = pageToObj(data).items[0];
                    if (callback) {
                        callback(formData);
                    }
                }
            });
        },
        modify: function (formData, callback) {
            $.ajax({
                url: window.BASE_URL + '/common/device' + (formData.id ? ("/" + formData.id) : ''),
                type: formData.id ? "PUT" : "POST",
                data: JSON.stringify(formData),
                dataType: "json",
                success: function (data) {
                    if (callback) {
                        callback();
                    }
                }
            });
        }
    }

    $scope.setLabel = function (item) {
        var label = prompt("请输入标签：", item.language);
        if (!label) return;
        else {
            item.language = label;
            $scope.deviceInput.load(item.id, function (formData) {
                formData.language = label;
                $scope.deviceInput.modify(formData, function () {
                    alert('保存成功');
                    applyAngularScope($rootScope, $scope);
                });
            });
        }
    }

    $scope.setTableData = function (items) {
        $scope.pageData.items = items;
        applyAngularScope($rootScope, $scope);
    }
    $scope.search = function () {
        $scope.queryParams.word = $scope.word;
        $scope.queryParams.pageNo = 1;
        loadData();
    }

    $scope.goPage = function (pageNo, className) {
        if (className == 'disabled') {
            return;
        }
        $scope.queryParams.pageNo = pageNo;
        loadData();
    }

    $("#searchFiled").keydown(function (e) {
        var curKey = e.which;
        if (curKey == 13) {
            $scope.search();
            return false;
        }
    });

    $scope.sendMsg = function (item) {
        $("#msgModal").modal("show").on("hidden", function () {
            $scope.msg = null;
            applyAngularScope($rootScope, $scope);
        });
    }

    $scope.showApps = function (item) {
        top.CurrentDeviceApps = item.id;
        top.commonModal.show("./device/popapps.html", "查看应用列表", function () {
            alert("hello");
        });
    }
    $scope.showLogs = function (item) {
        top.CurrentDeviceLog = item.id;
        top.commonModal.show("./device/poplogs.html", "查看应用列表", function () {
            alert("hello");
        });
    }

    $scope.CheckController = {
        ckAllItems: function (pageData) {
            if (pageData) {
                pageData.ckAll = !pageData.ckAll;
                $.each(pageData.items, function (i, item) {
                    if (!item.conn) {
                        item.checked = false;
                    } else {
                        item.checked = pageData.ckAll;
                        $scope.AndroidCtroller.disabled = !pageData.ckAll;
                    }
                });

                applyAngularScope($rootScope, $scope);
            }
        },
        ckItem: function (item, pageData) {
            if (item) {
                item.checked = !item.checked;
                if (!item.checked) {
                    pageData.ckAll = false;
                }

                $scope.AndroidCtroller.disabled = true;
                $.each(pageData.items, function (i, d) {
                    if (d.checked) {
                        $scope.AndroidCtroller.disabled = false;
                        return false;
                    }
                });
                applyAngularScope($rootScope, $scope);
            }
        },
        getCheckedItems: function (pageData) {
            var arr = new Array();
            if (pageData && pageData.items) {
                $.each(pageData.items, function (i, item) {
                    if (item.checked) {
                        arr.push(item);
                    }
                });
            }
            return arr;
        },
        ckIsSelectItems: function (arr) {
            if (arr && arr.length > 0) {
                return confirm("是否执行该操作?");
            } else {
                alert("请选择要操作的设备！");
                return false;
            }
        }

    }

    $scope.AndroidCtroller = {
        disabled: true,
        wipeType: {
            restoreType: "wipe-data",
            clearSDType: "wipe-all-sdcards",
            alarmType: "alarm"
        },
        command: {
            lockOrUnlockData: function (deviceId, pwd) {
                var body = {};
                if (pwd) {
                    body = {password: pwd};
                } else {
                    body = {unlock: true};
                }
                //准备要发送的命令
                var data = {
                    id: genUUID(),
                    type: "post",
                    status: 0,
                    path: "/systemCommTo",
                    header: {
                        to: deviceId
                    },
                    body: {
                        path: '/common/device/lockScreen',
                        type: 'post',
                        body: body
                    }
                };
                return data;
            },
            lockNetwork: function (deviceId, time) {
                var body = {time: time * 60 * 1000};
                //准备要发送的命令
                var data = {
                    id: genUUID(),
                    type: "post",
                    status: 0,
                    path: "/systemCommTo",
                    header: {
                        to: deviceId
                    },
                    body: {
                        path: '/common/device/lockNetwork',
                        type: 'post',
                        body: body
                    }
                };
                return data;
            },
            wipeData: function (deviceId, type) {
                var data = {
                    id: genUUID(),
                    type: "post",
                    status: 0,
                    path: "/systemCommTo",
                    header: {
                        to: deviceId
                    },
                    body: {
                        path: '/common/device/clearData',
                        type: 'put',
                        body: {
                            dataType: type
                        }
                    }
                };
                return data;
            },
            sendMsgData: function (deviceId, msg) {
                var data = {
                    id: genUUID(),
                    type: "post",
                    status: 0,
                    path: "/systemCommTo",
                    header: {
                        to: deviceId
                    },
                    body: {
                        path: '/msg/msg/sendText',
                        type: 'put',
                        body: {
                            title: msg.title,
                            content: msg.content
                        }
                    }
                };
                return data;
            }
        },
        /**
         * 锁屏
         */
        lockScreen: function () {
            var arr = $scope.CheckController.getCheckedItems($scope.pageData);
            if (!$scope.CheckController.ckIsSelectItems(arr)) return;
            var _self = this;
            var pwd = prompt("请输入锁屏密码：", "667788");
            if (!pwd) return;
            var reg = /^[0-9]{4,6}$/;
            if (!reg.test(pwd)) {
                alert("请输入4-6位数字锁屏密码！");
                return false;
            } else {

                for (var i in arr) {
                    var deviceItem = arr[i];
                    if (deviceItem.id) {
                        var data = _self.command.lockOrUnlockData(deviceItem.id, pwd);
                        _sendMsg(data, function (reqData, respData) {
                            if (data.item) {
                                alert("已锁屏！");
                                data.item.isLock = "已锁屏";
                                top.LOADING.isShow = true;
                                $scope.deviceInput.load(data.item.id, function (formData) {
                                    formData.isLock = true;
                                    top.LOADING.isShow = true;
                                    $scope.deviceInput.modify(formData, function () {
                                        top.LOADING.isShow = false;
                                    });
                                });
                                data.item = false;
                            }
                            applyAngularScope($rootScope, $scope);
                        });
                        data.item = deviceItem;
                    }
                }
            }
        },
        /**
         *解屏
         */
        unlock: function () {
            var arr = $scope.CheckController.getCheckedItems($scope.pageData);
            if (!$scope.CheckController.ckIsSelectItems(arr)) return;
            var _self = this;
            var arr = $scope.CheckController.getCheckedItems($scope.pageData);
            for (var i in arr) {
                var deviceItem = arr[i];
                if (deviceItem.id) {
                    var data = _self.command.lockOrUnlockData(deviceItem.id, false);
                    _sendMsg(data, function (reqData, respData) {
                        if (data.item) {
                            alert("已解锁！");
                            data.item.isLock = "";
                            top.LOADING.isShow = true;
                            $scope.deviceInput.load(data.item.id, function (formData) {
                                formData.isLock = false;
                                top.LOADING.isShow = true;
                                $scope.deviceInput.modify(formData, function () {
                                    top.LOADING.isShow = false;
                                });
                            });
                            data.item = false;
                        }
                        applyAngularScope($rootScope, $scope);
                    });
                    data.item = deviceItem;
                }
            }
        },
        /**
         * 发送报警
         */
        warnBell: function () {
            //alert("发送报警");
            var arr = $scope.CheckController.getCheckedItems($scope.pageData);
            if (!$scope.CheckController.ckIsSelectItems(arr)) return;
            var _self = this;

            for (var i in arr) {
                var item = arr[i];
                if (item.id) {
                    var data = _self.command.wipeData(item.id, _self.wipeType.alarmType);
                    _sendMsg(data, function () {
                        alert('警报发送成功！');
                    });
                }
            }
        },
        /**
         * 清除数据
         */
        clearSDData: function () {
            // alert("擦除数据");
            var arr = $scope.CheckController.getCheckedItems($scope.pageData);
            if (!$scope.CheckController.ckIsSelectItems(arr)) return;
            var _self = this;

            for (var i in arr) {
                var item = arr[i];
                if (item.id) {
                    var data = _self.command.wipeData(item.id, _self.wipeType.clearSDType);
                    _sendMsg(data, function () {
                        alert('擦除数据成功！');
                    });
                }
            }
        },
        /**
         * 恢复出厂设置
         */
        restore: function () {
            // alert("恢复出厂设置");
            var arr = $scope.CheckController.getCheckedItems($scope.pageData);
            if (!$scope.CheckController.ckIsSelectItems(arr)) return;
            var _self = this;

            for (var i in arr) {
                var item = arr[i];
                if (item.id) {
                    var data = _self.command.wipeData(item.id, _self.wipeType.restoreType);
                    _sendMsg(data, function () {
                        alert('恢复出厂设置成功！');
                    });
                }
            }
        },
        /**
         * 推送消息
         */
        sendMsg: function (msg) {
            if (!msg || !msg.title || !msg.content) {
                alert("请输入要发送的消息！");
                return false;
            }
            var arr = $scope.CheckController.getCheckedItems($scope.pageData);
            if (!$scope.CheckController.ckIsSelectItems(arr)) return;
            var _self = this;

            for (var i in arr) {
                var item = arr[i];
                if (item.id) {
                    var data = _self.command.sendMsgData(item.id, msg);
                    _sendMsg(data, function () {
                        alert('消息发送成功！');
                    });
                }
            }
            $("#msgModal").modal("hide");
        },
        /**
         * 网络控制
         */
        network: function () {
            var arr = $scope.CheckController.getCheckedItems($scope.pageData);
            if (!$scope.CheckController.ckIsSelectItems(arr)) return;
            var _self = this;
            var time = prompt("请输入网络限制时间(1-99分钟)：", "40");
            if (!time) return;
            var reg = /^[0-9]{1,2}$/;
            if (!reg.test(time)) {
                alert("请输入有效控制时间(1-99分钟)！");
                return false;
            } else {

                for (var i in arr) {
                    var item = arr[i];
                    if (item.id) {
                        var data = _self.command.lockNetwork(item.id, time);
                        _sendMsg(data, function (reqData, respData) {
                            alert("网络控制已生效！");
                        });
                    }
                }
            }
        },
        /**
         *远程定位
         */
        location: function () {
            var arr = $scope.CheckController.getCheckedItems($scope.pageData);
            if (!$scope.CheckController.ckIsSelectItems(arr)) return;
            top.deviceControlMap = arr;
            top.commonModal.needreload = true;
            top.commonModal.show2("./maps.html", "查看设备位置", function () {
                top.deviceControlMap = null;
                top.commonModal.needreload = false;
            });
        }

    }

}